<template>
    <div
        class="progress-editor-outline flex flex-col w-80 max-h-screen overflow-y-auto sticky p-2 lg:p-4 text-sm top-0 z-20 bg-white">
        <p v-if="anchors && anchors.length > 0" class="font-semibold text-grey-900 dark:text-gray-300 leading-8 px-1">
            {{ i18n.t('outline') }}</p>
        <ul v-if="anchors && anchors.length > 0" class="text-gray-600 leading-8 px-2">
            <li v-for="item in anchors" key="item.id" class="border-l dark:border-gray-500"
                :style="{ paddingLeft: item.level + 'rem' }">
                <a class="block cursor-pointer"
                    :class="{ 'text-blue-500 dark:text-blue-400 font-bold': item.isActive, 'hover:text-blue-400 dark:hover:text-blue-300': !item.isActive, 'text-gray-500 dark:text-gray-500': item.isScrolledOver && !item.isActive, 'text-gray-700 dark:text-gray-400': !item.isScrolledOver && !item.isActive }"
                    @click.stop=onItemClick(item)>
                    <RemixIcon v-if="item.level > 1" name="arrow-right-s-line" />
                    {{ item.textContent }}
                </a>
            </li>
        </ul>
    </div>
</template>
<script setup>
import { TextSelection } from '@tiptap/pm/state'
import RemixIcon from './RemixIcon.vue'
import i18n from '../i18n';
import { watch, nextTick } from 'vue'
const props = defineProps({
    editor: {
        type: Object,
        default: () => {
            return {}
        }
    },
    anchors: {
        type: Array,
        default: () => []
    },
    activeAnchor: {
        type: String,
        default: ''
    }
})
const emits = defineEmits(['active'])
const onItemClick = (item) => {
    if (props.editor) {
        const element = props.editor.view.dom.querySelector(`[data-toc-id="${item.id}"`)
        const pos = props.editor.view.posAtDOM(element, 0)

        // set focus
        const tr = props.editor.view.state.tr

        tr.setSelection(new TextSelection(tr.doc.resolve(pos)))

        props.editor.view.dispatch(tr)

        props.editor.view.focus()

        emits('active', item.id)
    }
}
watch(() => props.activeAnchor, (value, oldValue) => {
    if (value && value !== oldValue) {
        nextTick(() => {
            onItemClick({ id: value})
        })
    }
}, { immediate: true });
</script>


<style lang='scss' scoped></style>